package com.tianqu.tms.www.car.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsAjaxAction;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.entity.Car;
import com.tianqu.tms.entity.Member;

/**
 *  mufeiyu
 */
public class CarMemberNameListAjaxAction extends TmsAjaxAction{
	private Logger logger = Logger.getLogger(CarMemberNameListAjaxAction.class);
	@Override
	public void process( ActionMapping mapping, ActionForm form
	                                          , HttpServletRequest request
	                                          , HttpServletResponse response
	                                          , UserContext uc)throws TmsException {
		
		logger.debug(this.getClass().getName() + "#execute.");
		
		String query = request.getParameter("query");
		String strFlag = request.getParameter("flag");
		String type = request.getParameter("type");
		int flag = 0;
		List list = new ArrayList();
		Map map = null;
		
		if (!StringUtil.isNullOrBlank(strFlag)) {
			flag = StringUtil.getint(strFlag);
		}
		Member member = Member.getInstance();

		List<Member> mInfoList = member.findMemberNameList(query,flag);
		boolean isCar = false;
		if(!StringUtil.isEmpty(type) && "car".equals(type)) {
			isCar = true;
		}

		Car carInfo = Car.getInstance();
		for (Member mInfo:mInfoList) {
			map = new HashMap();
			if(isCar) {

				//通过所选商户ID到商户会员信息数据表（tms_member）中，查询对应的允许登记数量（annualTransactionVolume）
				int annualTransactionVolume = member.findAnnualTransactionVolume(String.valueOf(mInfo.getMemId()));

				
				//再到库存车辆信息表（tms_market_car_info）中，获取商户会员ID为当前选择商户ID 并且 车辆库存状态为“1：已入库；2：已出库；6：登记”的数据总数
				int alreadyTransactionVolume = carInfo.getAlreadyTransactionVolumeByMemberId(String.valueOf(mInfo.getMemId()));
				
				//如果所得到数据总数大于或者等于允许库存登记数量，那么停止当前操作，页面提示“【U8004】当前商户的允许登记数量已经用完，无法进行保存。”
				if (alreadyTransactionVolume < annualTransactionVolume) {
					map.put("value", mInfo.getShortName()+"["+mInfo.getRealNamePy()+"]");
					map.put("data", mInfo.getMemId());
					list.add(map);
				}
				
			} else {
				map.put("value", mInfo.getShortName()+"["+mInfo.getRealNamePy()+"]");
				map.put("data", mInfo.getMemId());
				list.add(map);
			}
			
		}

		 JSONArray jsonArray =  JSONArray.fromObject(JSONArray.fromObject(list));

		 JSONObject json =new JSONObject(); 
		 json.put("query", query);
		 json.put("suggestions", jsonArray);
		 
		responseValues(response, json.toString(), TEXT);

		logger.debug(this.getClass().getName() + "#doAction was completed.");
	}
}
